package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.location.Location;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemoUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	JmsTemplate jmsTemplate;

	/**
	 * 发送手机验证码
	 * @return
	 * @throws Exception
	 */
	@Action(value = "customer_sendSms",results={@Result(name="success",type="json")})
	public String  sendSms() throws Exception {
		//获取手机号
		final String telephone = model.getTelephone();
		//生成四位验证码
		final String randomCode = SmsDemoUtils.getNumber();
		//将手机号码放在session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(1*60);//设置session失效
		//SendSmsResponse sendSms = SmsDemoUtils.sendSms(telephone, randomCode);
		//使用短信平台系统(bos_sms)负责发送短息,使用消息队列ActiveMQ,此时bos_fore为生产者
		//调用MQ服务,发送一条消息
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", telephone);
				mapMessage.setString("code", randomCode);
				return mapMessage;
			}
		});
		
		
		
		
		String sendSms = "OK";
		//发送成功
		if (sendSms.equals("OK")) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("success", randomCode);
			map.put("telephone", telephone);
			map.put("code", randomCode);
			ServletActionContext.getContext().getValueStack().push(map);
		}else {
			throw new RuntimeException("请联系管理员");
		}
		return SUCCESS;
	}
	/**
	 * 进行注册功能
	 * 
	 * @return
	 */
	private String checkcode;
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	@Action(value = "customer_regist",results={@Result(name="success",type="redirect" ,location="signup-success.html"),
			@Result(name="input",type="redirect" ,location="signup.html")})
	public String  regist()  {
		//先校验短信验证信息
		//从session中获取之前生成的验证码
		String checkcodeSession=(String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (checkcodeSession==null || !checkcodeSession.equals(checkcode)) {
			System.out.println("短信验证码错误");
			return INPUT;
		}
		
		//完成注册
		WebClient.create(Constants.CRM_MANAGEMENT_URL)
				.path("/services/customerService/customer")
				.type(MediaType.APPLICATION_JSON)
				.post(model);
		
		//向redis数据库存放邮件的激活码,激活码的生命周期为一天(24h)
		//调用mailUtils发送一封邮件
		
		//生成32位的激活码
		String activecode = RandomStringUtils.randomNumeric(32);
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		
		MailUtils.sendMail("苏云快递", content, model.getEmail(), "");
		return SUCCESS;
	}
	
	/**
	 * 邮箱激活
	 */
	
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	@Action(value="customer_activeMail")
	public String activeMail() throws IOException {
		 ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		//判断激活码是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activecodeRedis==null|| !activecode.equals(activecodeRedis)) {
			//激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		
		}
			//激活码有效
			//判断是否重复绑定
			//调用crm查询type信息
			Customer customer = WebClient
					.create(Constants.CRM_MANAGEMENT_URL)
					.path("/services/customerService/customer/telephone/"+model.getTelephone())
					.accept(MediaType.APPLICATION_JSON)
					.type(MediaType.APPLICATION_JSON)
					.get(Customer.class);
			
			if (customer!=null && customer.getType() !=1) {
				WebClient
					.create(Constants.CRM_MANAGEMENT_URL)
					.path("/services/customerService/customer/updatetype/"+model.getTelephone())
					.type(MediaType.APPLICATION_JSON)
					.put(model);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
				
			}else {
				// 已经绑定过
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
			}
			
			redisTemplate.delete(model.getTelephone());
			
		
		return NONE;
		
	}
	
	/**
	 * 前台登录
	 */
	@Action(value = "customer_login",results={@Result(name="success",type="redirect",location="./index.html#/myhome"),
			@Result(name="input",type="redirect",location="login.html")})
	public String  login()  {
		System.out.println("1111111");
		Customer customer = WebClient
		.create(Constants.CRM_MANAGEMENT_URL+
				"/services/customerService/customer/findByTelephoneAndPassword?telephone="
				+model.getTelephone()+"&password="+model.getPassword())
				.accept(MediaType.APPLICATION_JSON)
				.get(Customer.class);
		// 账号和密码输入有误
				if(customer==null){
					System.out.println("当前电话号："+model.getTelephone()+"登录或者密码错误！！");
					return LOGIN;
				}
				else{
					if(customer.getType()!=1){
						System.out.println("当前电话号："+model.getTelephone()+"，邮箱："+model.getEmail()+"没有激活！！");
						return LOGIN;
					}
					// 当前用户信息存放到Session中
					ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
					return SUCCESS;
					}
	
	
	
	}
	
	
	
	
	
	
	
}










